package com.lifesting.book.wci;

import java.io.IOException;
import java.io.InputStreamReader;

import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTreeNodeStream;
import org.antlr.runtime.tree.TreeNodeStream;

import wci.intermediate.SymTabEntry;
import wci.intermediate.SymTabStack;
import wci.intermediate.symtabimpl.SymTabKeyImpl;

import com.lifesting.book.wci.PascalParser.program_return;

public final class SimpleInterpreter {
	public static void main(String[] args) throws IOException, RecognitionException {
		//第5章示例Pascal
		InputStreamReader stream = new InputStreamReader(ShowToken.class.getResourceAsStream("/assignments.txt"));
		ANTLRReaderStream reader = new ANTLRReaderStream(stream);
		//词法分析器
		PascalLexer lexer = new PascalLexer(reader);
		CommonTokenStream token_stream = new CommonTokenStream(lexer);
		//语法分析器并带自己的TreeAdaptor，转换成自己的PascalNode
		PascalParser parser = new PascalParser(token_stream);
		parser.setTreeAdaptor(new PascalNodeAdaptor());
		program_return prog = parser.program();
		//遍历树并运算
		TreeNodeStream node_stream  = new CommonTreeNodeStream(prog.getTree());
		PascalVisitor interpreter = new PascalVisitor(node_stream);
		interpreter.program();
		SymTabStack stack = interpreter.getSymbolTableStack();
		SymTabEntry five_entry = stack.lookup("five");
		System.out.println("Five = "+five_entry.getAttribute(SymTabKeyImpl.DATA_VALUE));
		SymTabEntry str_entry = stack.lookup("str");
		System.out.println("str = "+str_entry.getAttribute(SymTabKeyImpl.DATA_VALUE));
		SymTabEntry  fahrenheit_entry = stack.lookup("fahrenheit");
		System.out.println("fahrenheit = "+fahrenheit_entry.getAttribute(SymTabKeyImpl.DATA_VALUE));
		SymTabEntry centigrade_entry = stack.lookup("centigrade");
		System.out.println("centigrade = "+centigrade_entry.getAttribute(SymTabKeyImpl.DATA_VALUE));
	}
}
